import axios from 'axios';

export default {
    state: {
        id: "",
        username: "",
        photo: "",
        token: "",
        is_login: false,
        pulling_info: true,  // 是否正在从云端拉取信息
    },
    getters: {
    },
    mutations: {
        updateUser(state, user) {
            state.id = user.id;
            state.username = user.username;
            state.photo = user.photo;
            state.is_login = user.is_login;
        },
        updateToken(state, token) {
            state.token = token;
        },
        logout(state) {
            state.id = "";
            state.username = "";
            state.photo = "";
            state.token = "";
            state.is_login = false;
        },
        updatePullingInfo(state, pulling_info) {
            state.pulling_info = pulling_info;
        }
    },
    actions: {
        login(context, data) {
            axios.post("http://127.0.0.1:3000/api/user/account/token/",{
                username: data.username,
                password: data.password,
            }).then(resp=>{
                if(resp.data.result === "success"){
                    localStorage.setItem("jwt_token",resp.data.jwt_token);
                    context.commit("updateToken",resp.data.jwt_token);
                    data.success(resp.data);
                    console.log(resp.data);
                }else{
                    data.error(resp.data);
                }
            }).catch(error=>{
                const errorResponse = error.response?error.response.data:error;
                data.error(errorResponse);
            })
        },
        getinfo(context, data){
            axios.get("http://127.0.0.1:3000/api/user/account/info/",{
                headers: {
                    Authorization: "Bearer " + context.state.token,
                },
            }).then(resp=>{
                if(resp.data.result === "success"){
                    context.commit("updateUser",{
                        ...resp.data,
                        is_login: true,
                    });
                    data.success(resp.data);
                }else{
                    data.error(resp.data);
                }
            }).catch(resp=>{
                console.log("context.state.token:",context.state.token);
                data.error(resp.data);
            })
        },
        logout(context) {
            localStorage.removeItem("jwt_token");
            context.commit("logout");
        }
    },
    modules: {
    }
}
